<template>
  <BottomDrawer
    :visible="addVisible"
    :title="'患者信息'"
    :width="900"
    @close="addVisible = false"
  >
    <div class="form-container">
      <form>
        <div class="form-row">
          <div class="form-item">
            <label for="name"><span class="required">*</span>姓名</label>
            <input type="text" id="name" v-model="formData.patientName" />
          </div>
          <div class="form-item">
            <label for="gender"><span class="required">*</span>性别</label>
            <div class="gender-select-container">
              <div
                class="gender-option"
                :class="{ active: patientSex === '男' }"
                @click="onPatientSex('男')"
              >
                男
              </div>
              <div
                class="gender-option"
                :class="{ active: patientSex === '女' }"
                @click="onPatientSex('女')"
              >
                女
              </div>
            </div>
          </div>
          <div class="form-item">
            <label for="phone"><span class="required">*</span>电话</label>
            <input type="text" id="phone" v-model="formData.patientPhone" />
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label for="idNumber">身份证号</label>
            <input type="text" id="idNumber" v-model="formData.idCard" />
          </div>
          <div class="form-item">
            <label for="solarBirthday">阳历生日</label>
            <el-date-picker
              type="date"
              v-model="formData.solarBirthday"
              placeholder="选择阳历生日"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
            <div class="input__prefix">
              <img src="@/assets/icon/calendar.svg" alt="" />
            </div>
          </div>
          <div class="form-item">
            <label for="lunarBirthday">阴历生日</label>
            <el-date-picker
              type="date"
              placeholder="选择阴历生日"
              format="YYYY-MM-DD"
              v-model="formData.lunarBirthday"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            >
            </el-date-picker>
            <div class="input__prefix">
              <img src="@/assets/icon/calendar.svg" alt="" />
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label for="height">身高</label>
            <el-input type="text" v-model="formData.height">
              <template #suffix> cm </template>
            </el-input>
          </div>
          <div class="form-item">
            <label for="weight">体重</label>
            <el-input type="text" v-model="formData.weight">
              <template #suffix> kg </template>
            </el-input>
          </div>
          <div class="form-item">
            <label for="bloodPressure">血压</label>
            <div class="blood-pressure-input-container">
              <input
                type="text"
                class="pressure-input"
                v-model="formData.systolicBp"
                placeholder="收缩压"
              />
              <span class="separator">/</span>
              <input
                type="text"
                class="pressure-input"
                v-model="formData.diastolicBp"
                placeholder="舒张压"
              />
              <span class="unit">mmHg</span>
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label for="ethnicity">民族</label>
            <!-- <input type="text" id="ethnicity" /> -->
            <el-select
              placeholder="Select"
              style="width: 240px"
              v-model="formData.ethnicity"
            >
              <el-option
                v-for="item in ethnicityEnum"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="form-item">
            <label for="gender"><span class="required">*</span>是否已婚</label>
            <div class="gender-select-container">
              <div
                class="gender-option"
                :class="{ active: marriage === '已婚' }"
                @click="onMarriage('已婚')"
              >
                已婚
              </div>
              <div
                class="gender-option"
                :class="{ active: marriage === '未婚' }"
                @click="onMarriage('未婚')"
              >
                未婚
              </div>
            </div>
          </div>
          <div class="form-item">
            <label for="bloodPressure">年龄</label>
            <div class="blood-pressure-input-container">
              <input
                type="text"
                class="pressure-input"
                v-model="formData.ageMonth"
              />
              <span class="separator">岁</span>
              <input
                type="text"
                class="pressure-input"
                v-model="formData.ageYear"
              />
              <span class="unit">月</span>
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label for="unit">单位</label>
            <input type="text" id="unit" v-model="formData.company" />
          </div>
          <div class="form-item">
            <label for="occupation">职业</label>
            <input type="text" id="occupation" v-model="formData.job" />
          </div>
        </div>
        <div class="form-item full-width">
          <label for="address">家庭住址</label>
          <input type="text" id="address" v-model="formData.address" />
        </div>
        <div class="form-item full-width">
          <label for="remarks">备注</label>
          <input type="text" id="remarks" v-model="formData.remark" />
        </div>

        <div class="history-form">
          <div class="table-container">
            <div class="table-row">
              <div class="table-cell label-cell">
                <span>既往史</span>
              </div>
              <div class="table-cell input-cell">
                <input
                  type="text"
                  id="medicalHistory"
                  @focus="onBlur"
                  v-model="formData.medicalHistory"
                />
                <div style="position: absolute; bottom: 86px" v-if="isPatient">
                  <Medical
                    :medicalList="medicalList"
                    @on-close="onClose"
                    @onSymptom="onSymptom"
                  ></Medical>
                </div>
              </div>
            </div>
            <div class="table-row">
              <div class="table-cell label-cell">过敏史</div>
              <div class="table-cell input-cell">
                <input
                  type="text"
                  id="allergyHistory"
                  @focus="onBlur_1"
                  v-model="formData.allergyHistory"
                />
                <div style="position: absolute; bottom: 86px" v-if="isPatient">
                  <Medical
                    :medicalList="medicalList"
                    @on-close="onClose"
                    @onSymptom="onSymptom"
                  ></Medical>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
      <el-button
        style="float: right; margin-top: 20px"
        type="primary"
        @click="onAddPatient"
        >保存</el-button
      >
    </div>
  </BottomDrawer>
</template>

<script setup lang="ts">
import { ref, shallowRef, reactive } from 'vue';
import { Calendar } from '@element-plus/icons-vue';
import { addPatient, getPatientMedicalField } from '@/api/patient';
import store from '@/store';
const medicalList = ref([]);
const medicalResponse = ref([]);
// 这里可以添加组件的逻辑代码，例如数据绑定、事件处理等

defineExpose<{
  open: () => void;
}>({
  open: async () => {
    addVisible.value = true;
    const refult = await getPatientMedicalField();
    if (refult && refult.data) {
      medicalResponse.value = refult.data;
    }
  },
});
const userEnums = store.useBaseDataStore();
const ethnicityEnum = userEnums.getEnumSelect('ethnicityEnum');
// 使用 shallowRef 或 markRaw 处理组件
const calendarIcon = shallowRef(Calendar);
const addVisible = ref(false);
const selectedGender = ref('男');
const formData = ref({
  patientName: '', //患者名
  patientSex: '', //患者性别;1男生2女生3未知SexEnum
  patientPhone: '', //患者电话
  idCard: '', //身份证号
  ageYear: 0, //年龄年;5代表5岁
  ageMonth: 0, //年龄月;2代表2个月
  lunarBirthday: '', //阴历生日
  solarBirthday: '', //阳历生日
  weight: null, //体重;53.8kg
  systolicBp: null, //收缩压;120mmHg
  diastolicBp: null, //舒张压;80mmHg
  height: null, //身高;183cm
  ethnicity: '1', //民族EthnicityEnum
  isMarried: '1', //婚否;1是0否YesOrNoEnum
  company: '', //单位
  job: '', //职业
  province: '', //省份
  city: '', //市区
  county: '', //县
  address: '', //家庭住址
  medicalHistory: '', //既往史
  allergyHistory: '', //过敏史
  remark: '', //备注
  lastRechargeTime: '', // 新增属性，最后充值时间
  fieldList: [], // 新增属性，字段列表
});
const marriage = ref('已婚');
const patientSex = ref('男');
const solarBirthday = ref('');
const lunarBirthday = ref('');
const isPatient = ref(false);
const ethnicityList = ref([
  { label: '汉族', value: '汉族' },
  { label: '满族', value: '满族' },
  { label: '回族', value: '回族' },
  { label: '藏族', value: '藏族' },
  { label: '维吾尔族', value: '维吾尔族' },
  { label: '苗族', value: '苗族' },
  { label: '彝族', value: '彝族' },
  { label: '壮族', value: '壮族' },
]);
const onMarriage = (value: string) => {
  marriage.value = value;
  formData.value.isMarried = value === '已婚' ? '1' : '0';
};
const selectGender = (gender: string) => {
  selectedGender.value = gender;
};
const onPatientSex = (value: string) => {
  if (value == '男') {
    formData.value.patientSex = '1';
  } else {
    formData.value.patientSex = '2';
  }
  patientSex.value = value;
};
// 病史
const onBlur = () => {
  // 这里可以添加失去焦点时的逻辑
  //console.log('输入框失去焦点');
  isPatient.value = true; // 设置为true表示有病史
  medicalList.value = medicalResponse.value[0] ?? [];
};
const onBlur_1 = () => {
  // 这里可以添加失去焦点时的逻辑
  //console.log('输入框失去焦点');
  isPatient.value = true; // 设置为true表示有病史
  medicalList.value = medicalResponse.value[1] ?? [];
};
const onClose = () => {
  isPatient.value = false; // 关闭病史弹窗
  medicalList.value = []; // 清空病史列表
};
// const onSymptom = (symptom: string) => {
//   // 这里可以添加选中症状的逻辑，例如将选中的症状传递给父组件
//   //console.log('选中的症状:', symptom);
//   formData.value.medicalHistory += symptom + ';'; // 将选中的症状添加到既往史中
// };
const onSymptom = (symptom: any) => {
  // 这里可以添加选中症状的逻辑，例如将选中的症状传递给父组件
  //console.log('选中的症状:', symptom);
  // 统一整理本次传入的症状列表
  // 统一整理本次传入的症状列表
  //   let incoming: string[] = [];
  //   if (Array.isArray(symptom)) {
  //     incoming = symptom
  //       .map((s: any) => (s?.text ?? s)?.toString().trim())
  //       .filter(Boolean);
  //   } else {
  //     incoming = [(symptom?.text ?? symptom)?.toString().trim()].filter(
  //       Boolean
  //     );
  //   }
  //   const sep = '，';
  // formData.value.medicalHistory += incoming.join(sep);// 将选中的症状添加到既往史中

  const prevRaw = (formData.value.medicalHistory ?? '').toString().trim();
  const existingSet = new Set(
    prevRaw
      ? prevRaw
          .split(/[，,]+/)
          .map((s: string) => s.trim())
          .filter(Boolean)
      : []
  );

  // 统一整理本次传入的症状列表
  let incoming: string[] = [];
  if (Array.isArray(symptom)) {
    incoming = symptom
      .map((s: any) => (s?.text ?? s)?.toString().trim())
      .filter(Boolean);
  } else {
    incoming = [(symptom?.text ?? symptom)?.toString().trim()].filter(Boolean);
  }

  // // 过滤掉已经存在的，避免重复
  // const newItems = incoming.filter((it) => !existingSet.has(it));
  // if (newItems.length === 0) return; // 没有新增内容则不更新

  // const sep = '，';
  // const prefix = prevRaw
  //   ? /[，,]$/.test(prevRaw)
  //     ? prevRaw
  //     : prevRaw + sep
  //   : '';
  let data = '';
  symptom.forEach((item: { type: any; text: any }) => {
    if (item.type) {
      data += `${item.text}`;
    } else {
      data += `，${item.text}`;
    }
  });
  // const appended = prefix + newItems.join(sep);
  formData.value.medicalHistory += data;
};
// 点击症状（支持单个或数组，追加而不覆盖，自动去重）
// const onSymptom = (symptom: any) => {
//   //console.log('选中的症状:', symptom);
//   fields.value.forEach((f) => {
//     if (f.fieldId !== focusedField.value) return;

//     const prevRaw = (f.content ?? '').toString().trim();
//     const existingSet = new Set(
//       prevRaw
//         ? prevRaw
//             .split(/[，,]+/)
//             .map((s: string) => s.trim())
//             .filter(Boolean)
//         : []
//     );

//     // 统一整理本次传入的症状列表
//     // let incoming: string[] = [];
//     // if (Array.isArray(symptom)) {
//     //   incoming = symptom
//     //     .map((s: any) => (s?.text ?? s)?.toString().trim())
//     //     .filter(Boolean);
//     // } else {
//     //   incoming = [(symptom?.text ?? symptom)?.toString().trim()].filter(
//     //     Boolean
//     //   );
//     // }

//     // // 过滤掉已经存在的，避免重复
//     // const newItems = incoming.filter((it) => !existingSet.has(it));
//     // if (newItems.length === 0) return; // 没有新增内容则不更新
//     // const sep = '，';
//     let data = '';
//     symptom.forEach((item: { type: any; text: any }) => {
//       if (item.type) {
//         data += `${item.text}`;
//       } else {
//         data += `,${item.text}`;
//       }
//     });
//     // const prefix = prevRaw
//     //   ? /[，,]$/.test(prevRaw)
//     //     ? prevRaw
//     //     : prevRaw + sep
//     //   : '';
//     // const appended = prefix + newItems.join(sep);
//     f.content += data;
//     f.fieldValue += data;
//   });

//   // triggerRef(fields); // 触发视图更新
// };

const onAddPatient = async () => {
  // 这里可以添加保存患者信息的逻辑
  const data = await addPatient(formData.value);
  if (data.code == '200') {
    //console.log('患者信息保存成功:', data);
    ElMessage({
      type: 'success',
      message: '患者信息保存成功',
    });
    addVisible.value = false; // 关闭弹窗
    formData.value = {
      patientName: '', //患者名
      patientSex: '', //患者性别;1男生2女生3未知SexEnum
      patientPhone: '', //患者电话
      idCard: '', //身份证号
      ageYear: 0, //年龄年;5代表5岁
      ageMonth: 0, //年龄月;2代表2个月
      lunarBirthday: '', //阴历生日
      solarBirthday: '', //阳历生日
      weight: null, //体重;53.8kg
      systolicBp: null, //收缩压;120mmHg
      diastolicBp: null, //舒张压;80mmHg
      height: null, //身高;183cm
      ethnicity: '1', //民族EthnicityEnum
      isMarried: '1', //婚否;1是0否YesOrNoEnum
      company: '', //单位
      job: '', //职业
      province: '', //省份
      city: '', //市区
      county: '', //县
      address: '', //家庭住址
      medicalHistory: '', //既往史
      allergyHistory: '', //过敏史
      remark: '', //备注
      lastRechargeTime: '', // 新增属性，最后充值时间
      fieldList: [], // 新增属性，字段列表
    };
  }
};
</script>

<style scoped lang="scss">
.form-container {
  padding: 20px;
  border-radius: 5px;
}

.form-row {
  display: flex;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  margin-right: 15px;
  position: relative;
}

.form-item:last-child {
  margin-right: 0;
}

.full-width {
  width: 100%;
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #666;
}

.required {
  color: red;
}

input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.gender-buttons,
.marital-buttons {
  display: flex;
}

.gender-buttons button,
.marital-buttons button {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
  background-color: white;
  cursor: pointer;
}

.gender-buttons button.active,
.marital-buttons button.active {
  background-color: #e0e0e0;
}

.unit {
  margin-left: 5px;
  color: #666;
}
.gender-select-container {
  display: flex;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  padding: 2px;
}

.gender-option {
  flex: 1;
  text-align: center;
  padding: 4px 0;
  cursor: pointer;
  color: #0c0c0c;
  background: #f5f5f5;
}

.gender-option.active {
  background: #ffffff;
  color: var(--el-color-primary);
}
.input__prefix {
  position: absolute;
  right: 15px;
  top: 30px;
}
.blood-pressure-input-container {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 5px;
  background: #ffffff;
}

.pressure-input {
  flex: 1;
  border: none;
  outline: none;
  padding: 0 8px;
}

.separator {
  margin: 0 8px;
  color: #666;
}

.unit {
  color: #666;
}

.history-form {
  position: relative;
  .table-container {
    width: 100%;
    background: #f5fefd;
    border: 1px solid #dcdcdc;
    border-radius: 4px;
  }

  .table-row {
    display: flex;
    flex-direction: row;
    border-bottom: 1px solid #b3cfe4;

    &:last-child {
      border-bottom: none;
    }
  }

  .table-cell {
    height: 40px;
    display: flex;
    align-items: center;

    &.label-cell {
      width: 12%;
      padding: 0 20px;
      text-align: center;
      border-right: 1px solid #b3cfe4;
    }

    &.input-cell {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 20px;

      input[type='text'] {
        flex: 1;
        border: none;
        background-color: transparent;
        padding: 5px;
      }

      .checkbox-container {
        display: flex;
        align-items: center;

        input[type='checkbox'] {
          margin-left: 10px;
        }
      }
    }
  }
}
::v-deep(.modal-footer) {
  border: none;
}
</style>
<style lang="scss">
.form-item {
  .el-input__prefix {
    display: none;
    position: relative;
  }
  .el-input__suffix-inner {
    color: #666;
  }
}
</style>
